<!--
 * @Date: 2022-04-11 18:24:17
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-08-05 09:32:13
 * @FilePath: \imitation-microblog-vue\src\views\personal\index.vue
 * @Description: 个人信息主页
-->
<template>
  <div class="personalContainer">
    <div class="bgImg">
      <img :src="userInfo?.avatar" class="avatarBG" />
    </div>
    <div class="userInfo">
      <div class="avatarAndName">
        <div class="avatar" @click="preview(userInfo?.avatar!)">
          <img :src="userInfo?.avatar" alt="" />
        </div>
        <div class="baseInfo">
          <div class="nickName">
            <span>{{ userInfo?.nickName }}</span>
            <i
              class="iconfont"
              :class="
                userInfo?.gender == 1
                  ? 'icon-nan nan'
                  : userInfo?.gender == 0
                  ? 'icon-nv nv'
                  : ''
              "
            ></i>
          </div>
          <div class="fansAndFollw">
            <div class="followBox" @click="goFollowing">
              关注：
              <div class="count" :data-target="followCount"></div>
            </div>
            <div class="fansBox" @click="goFans">
              粉丝：
              <div class="count" :data-target="fansCount"></div>
            </div>
          </div>
          <div class="btns" v-if="store.state.userInfos.id !== userInfo?.id">
            <div
              class="btn"
              @click="followUser(userInfo?.id)"
              v-if="followBack"
            >
              <i class="iconfont icon-jia"></i>
              回关
            </div>
            <div
              class="unbtn"
              v-else-if="showUnFollow"
              @click="unFollowing(userInfo?.id)"
            >
              取消关注
            </div>
            <div class="btn" v-else @click="followUser(userInfo?.id)">
              <i class="iconfont icon-jia"></i>
              关注
            </div>
          </div>
        </div>
      </div>
      <!-- 各种介绍 -->
      <div class="deepInfo">
        <div class="itembox">
          <i class="iconfont icon-jibenxinxi"></i
          >{{ userInfo.description ? userInfo.description : "暂无简介" }}
        </div>
        <div class="itembox">
          <i class="iconfont icon-didiandingwei_o"></i
          >{{ userInfo.city ? userInfo.city : "暂无定位" }}
        </div>
        <div class="itembox">
          <i class="iconfont icon-riqi_o"></i
          >{{ DateFormat(userInfo?.createdAt) }}
          创建
        </div>
      </div>
    </div>
  </div>

  <div
    class="blogList"
    v-if="blogCount !== 0"
    v-infinite-scroll="loadMoreBlog"
    :infinite-scroll-disabled="disabledLoad"
    infinite-scroll-delay="500"
  >
    <div style="margin: 5px; font-size: 14px">全部内容({{ blogCount }})</div>
    <template v-for="(item, index) in BlogList" :key="item.id">
      <wei-bo-content-card :BlogBaseInfo="item"></wei-bo-content-card>
    </template>
  </div>
  <div v-else><el-empty description="暂无内容" /></div>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
import { DateFormat } from "../../utils/tools";
import { UserData } from "./types";
import weiBoContentCard from "../../components/weiBoContentCard/index.vue";
import {
  BlogListType,
  followListType,
} from "../../components/createWeiBo/types";
import { ElMessage } from "element-plus";
import router from "../../router";
import debounce from "lodash/debounce";
const { $api, $bus } =
  getCurrentInstance()!.appContext.config.globalProperties!;
const route = useRoute();
const store = useStore();
let userInfo = ref<UserData>({});
let BlogList = ref<BlogListType[]>([]);
let currentPage = ref<number>(1);
let pageSize = ref<number>(5);
let blogCount = ref<number>(0);
let disabledLoad = ref<boolean>(false);
let followCount = ref(0);
let fansCount = ref(0);
//显示回关
let followBack = ref<boolean>(false);
// 显示取消关注
let showUnFollow = ref<boolean>(false);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
//数字动画
const numTrasition = () => {
  const fanscounts = document.querySelectorAll(".count");
  fanscounts.forEach((count: any) => {
    count.innerText = "0";
    function updateFans() {
      const nowFans = +count.getAttribute("data-target")!;
      let fans = +count.innerText;
      let num = nowFans / 10;
      if (fans < nowFans) {
        count.innerText = `${Math.ceil(fans + num)}`;
        setTimeout(updateFans, 40);
      } else {
        count.innerText = nowFans;
      }
    }
    updateFans();
  });
};
//获取用户信息
const getUserInfoById = async (id: number) => {
  let res = await $api.user.reqOtherUserInfo(id);
  if (res.code == 200) {
    userInfo.value = res.data;
  }
};
//获取微博列表
const getBlogList = async (
  currentPage: number,
  pageSize: number,
  id: number
) => {
  let res = await $api.blog.reqBlogList(currentPage, pageSize, id);
  if (res.code == 200) {
    blogCount.value = res.data.count;
    BlogList.value?.push(...res.data.blogList);
  }
};
//获取更多博客列
const loadMoreBlog = () => {
  console.log("触底了");
  if (BlogList.value?.length == blogCount.value) {
    disabledLoad.value = true;
    ElMessage.error("没有更多了！");
    return;
  }
  currentPage.value++;
  getBlogList(currentPage.value, pageSize.value, +route.params.id);
};
//初始化
const init = (id: string) => {
  if (id == store.state.userInfos.id) {
    userInfo.value = store.state.userInfos as UserData;
    // console.log(userInfo?);
  } else {
    getUserInfoById(parseInt(id as string));
  }
};
//获取关注数量
const getFollowingCount = async (id: number) => {
  let res = await $api.user.reqFollowingList(id);
  if (res.code == 200) {
    followCount.value = res.data.count;
  }
  await nextTick();
  numTrasition();
};
//获取粉丝数量
const getFansCount = async (id: number) => {
  let res = await $api.user.reqFollowUserList(id);
  if (res.code == 200) {
    fansCount.value = res.data.count;
  }
  await nextTick();
  numTrasition();
};
//跳转关注列表
const goFollowing = () => {
  const id = route.params.id;
  router.push({ name: "Following", params: { id } });
};
//跳转粉丝列表
const goFans = () => {
  const id = route.params.id;
  router.push({ name: "Fans", params: { id } });
};
// 关注
const followUser = debounce(async (id: number) => {
  if (!store.state.isLogin) {
    ElMessage.error("请先登录！");
    return;
  }
  let res = await $api.user.reqFollowUser(id);
  if (res.code == 200) {
    ElMessage.success("关注成功");
    showUnFollow.value = true;
    $bus.emit("getFansData");
  }
}, 500);

//取消关注
const unFollowing = debounce(async (id: number) => {
  let res = await $api.user.reqUnFollowUser(id);
  if (res.code == 200) {
    ElMessage.success("取消关注成功！");
    $bus.emit("getFansData");
  }
}, 500);
//查看头像大图
const preview = (url: string) => {
  dialogImageUrl.value = url;
  dialogVisible.value = true;
};
onMounted(() => {
  init(route.params.id as string);
  getFollowingCount(+route.params.id);
  getFansCount(+route.params.id);
  getBlogList(currentPage.value, pageSize.value, +route.params.id);
});
watch(
  () => route.params.id,
  (val) => {
    if (val) {
      init(val as string);
      getBlogList(currentPage.value, pageSize.value, +route.params.id);
    }
  }
);
watch(
  () => store.state.fansData,
  async (val) => {
    followBack.value = val!.userList?.some((user: UserData, index: number) => {
      return user?.id == +route.params.id;
    })!;
  },
  { immediate: true }
);
watch(
  () => store.state.followingData,
  (val: followListType) => {
    showUnFollow.value = val.userList?.some((user, index: number) => {
      return user.user?.id == +route.params.id;
    })!;
    if (showUnFollow.value) {
      followBack.value = false;
    }
  },
  { immediate: true }
);
</script>

<style lang="less" scoped>
.personalContainer {
  height: 400px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border: 1px solid #ccc;
  .bgImg {
    height: 210px;
    overflow: hidden;
    position: relative;
    .avatarBG {
      z-index: -1;
      width: 100%;
      height: 100%;
      border-radius: 5px;
      filter: blur(20px) brightness(80%);
      overflow: hidden;
    }
  }
  .userInfo {
    flex: 1;
    display: flex;
    flex-direction: column;
    .avatarAndName {
      height: 80px;
      display: flex;
      // position: relative;
      .avatar {
        width: 6.25rem;
        height: 6.25rem;
        transform: translate(30px, -50px);
        margin-right: 50px;
        border: 5px solid #fff;
        border-radius: 50%;
        overflow: hidden;
        img {
          height: 100%;
          width: 100%;
          object-fit: cover;
          overflow: hidden;

          &:hover {
            transform: scale(1.2);
            filter: brightness(60%);
            cursor: pointer;
          }
        }
      }
      .baseInfo {
        flex: 1;
        position: relative;
        .nickName {
          margin-top: 5px;
          display: flex;
          align-items: center;
          span {
            font-size: 18px;
            font-weight: 700;
          }
        }
        .fansAndFollw {
          display: flex;
          margin-top: 5px;
          font-size: 14px;
          .followBox,
          .fansBox {
            display: flex;
            cursor: pointer;
            margin-right: 10px;
          }
          .count {
            margin-right: 10px;
            color: #696767;
            font-size: 14px;

            span {
              color: #000;
            }
          }
        }
        .btns {
          position: absolute;
          right: 10px;
          top: 10px;
          .btn,
          .unbtn {
            background-color: #ff8200;
            padding: 8px;
            border-radius: 20px;
            font-size: 12px;
            color: #fff;
            i {
              font-size: 12px;
            }
            &:hover {
              cursor: pointer;
              background-color: #ff5900;
            }
          }
          .unbtn {
            background-color: #ccc;
            width: 80px;
            text-align: center;
            &:hover {
              cursor: pointer;
              background-color: #939393;
            }
          }
        }
      }
    }
    .deepInfo {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 0 20px;
      color: #939393;
      font-size: 12px;
      .itembox {
        i {
          margin-right: 5px;
        }
      }
    }
  }
}
.blogList {
  margin-top: 10px;
}
.nan {
  color: #77c2f9;
  font-size: 18px;
}
.nv {
  color: pink;
  font-size: 18px;
}
.el-dialog {
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
